package com.starnet.yarnmonitor.yarn.utils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import com.starnet.yarnmonitor.yarn.conf.LinuxConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

@Component
public class LinuxUtils {
    @Autowired
    Environment environment;
    @Autowired
    LinuxConf linuxConf;

    public String shell(String command ) throws IOException {
        //创建连接
        Connection conn = new Connection(environment.getProperty("DB_HOST"));
        //连接服务器
        conn.connect();
        //用户登陆
        conn.authenticateWithPassword(linuxConf.getUser(), linuxConf.getPassword());

        //创建回话
        Session session = conn.openSession();
        //创建命令
        session.execCommand(command);
        //
        InputStream stdout = session.getStdout();
        byte[] bytes = stdout.readAllBytes();
        String linuxRes = new String(bytes, "UTF-8");

        session.close();
        conn.close();
        return linuxRes;
    }
}
